<?
require('../includes/class.main.php');
$manager = new MeetingManager();
require('../includes/class.geocode.php');


if (isset($_POST['submit']) && $_POST['submit'] == "Upload") {
	$errorcodes = array(
			UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
			UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
			UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
			UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
			UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
			UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
			UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
	);

	$result = "";
	$error = $_FILES['xlsdata']['error'];

	$target_path = "../xlsdata/meeting_data.xls";
	$tmp_path = $_FILES['xlsdata']['tmp_name'];
	$file_name = $_FILES['xlsdata']['name'];
	
	if ($error) { 
		
		$result = "<font color=\"red\">ERROR ($error):<br> $errorcodes[$error]</font>";
		
	} else { 
		
		if(!move_uploaded_file($tmp_path, $target_path)) {

			$result = "<font color=\"red\">ERROR: File moved failed. Check file permissions</font>";
		
		} else {
	
			chdir('../bin');
			$perlcmd = Props::get("exec", "perl");
		
			exec($perlcmd . ' ./MeetingDataLoad.pl ../xlsdata/meeting_data.xls', $output, $return);
		
			if ($return != 0) {
				$result = "<font color=\"red\">ERROR: File Upload Failed\n";
				$result .= "An error was encountered during processing. \n\n";
				
				foreach ($output as $line) {
					echo $line."\n";
					$result .= $line."\n";
				}
				$result .= "</font>";
			} else {
				
				$result .= "The " . $file_name . " file has been loaded successfuly.<br>";
				
				$geocoder = new GeocodeManager();

				$status = $geocoder->updateGeocodes();
				if ($status) {

					$result .= "<font color=\"red\">ERROR: $status</font><br>";
				
				} else {
				
					foreach ($geocoder->getGeocodes() as $geocoded) {
							
						if ($geocoded['status'] != "OK") {
							$result .= "<font color=\"red\">ERROR: Geocoding failed for ".$geocoded['address1']
							." ".$geocoded['city']." ".$geocoded['zip'].": ".$geocoded['status']."</font><br>";
						}
					}
				}
			}

			chdir('../admin');
		}
	}
		
	$_SESSION['updateStatus'] = $result;
}

header('Location: update-meetings.php', true, 303);
?>
